<script setup lang="ts">
import { ref, watch, defineEmits, onMounted, reactive } from 'vue';
import { Notification } from '@arco-design/web-vue';
import { getName, getUserJob } from '@/utils/auth';
import {
  getStocktaKingCode,
  getMaterialsByPlan,
  getMaterials,
  saveMaterials,
  inTrays,
} from '@/api/stocktaking';
import { outBatch } from '@/api/system-basic';
import { RowMaterial } from '@/api/stocktaking/types';

const modalVisible = ref(false);
const workTableData = ref<any[]>([]);
const needCheckTableData = ref<any[]>([]);
const trayTableData = ref<any[]>([]);
const detailTableData = ref<any[]>([]);
const materialCode = ref<string>('');
const stocktakingId = ref<string>('');
const rowClick = ref<RowMaterial | null>(null);
const selectedKeys = ref<string[]>();
const selectedRow = ref<any[]>([]);
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  onlyCurrent: false,
});

const workColumns: any[] = [
  {
    title: '作业列表',
    align: 'left',
    headerCellStyle: { fontSize: 'medium', fontWeight: 400 },
    children: [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
      },
      {
        title: '盘点单号',
        dataIndex: 'code',
        align: 'center',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      // {
      //   title: '是否大件',
      //   dataIndex: 'isLarge',
      //   slotName: 'isLarge',
      //   sortable: {
      //     sortDirections: ['ascend', 'descend'],
      //   },
      // },
    ],
  },
];

const needCheckColumns: any[] = [
  {
    title: '需盘物料列表',
    align: 'left',
    headerCellStyle: { fontSize: 'medium', fontWeight: 400 },
    children: [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
      },
      {
        title: '物料编码',
        dataIndex: 'materialCode',
        align: 'center',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '物料名称',
        dataIndex: 'materialName',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
    ],
  },
];

const trayColumns: any[] = [
  {
    title: '托盘列表',
    align: 'left',
    headerCellStyle: { fontSize: 'medium', fontWeight: 400 },
    children: [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
      },
      {
        title: '托盘/缓存箱编码',
        dataIndex: 'workbinCode',
        align: 'center',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
      {
        title: '当前状态',
        dataIndex: 'isBack',
        slotName: 'isBack',
        align: 'center',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
      },
    ],
  },
];

const detailColumns: any[] = [
  {
    title: '盘点明细',
    align: 'left',
    headerCellStyle: { fontSize: 'medium', fontWeight: 400 },
    children: [
      {
        title: '序号',
        dataIndex: 'index',
        slotName: 'index',
        align: 'center',
        width: 70,
      },
      {
        title: 'AO编码',
        dataIndex: 'aoCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '物料名称',
        dataIndex: 'materialName',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '物料编码',
        dataIndex: 'materialCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '物料图号',
        dataIndex: 'materialDrawingNo',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '物料型号',
        dataIndex: 'materialModelNo',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '物料规格',
        dataIndex: 'materialSpecifications',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '库存数量',
        dataIndex: 'inventoryQty',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 120,
      },
      {
        title: '托盘编码',
        dataIndex: 'palletCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '库存日期',
        dataIndex: 'inventoryDate',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 120,
      },
      {
        title: '库位编码',
        dataIndex: 'locationCode',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 140,
      },
      {
        title: '盘点数量',
        dataIndex: 'qty',
        slotName: 'qty',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 120,
      },
      {
        title: '盘点人',
        dataIndex: 'createUser',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 120,
      },
      // {
      //   title: '盘点时间',
      //   dataIndex: 'createTime',
      //   sortable: {
      //     sortDirections: ['ascend', 'descend'],
      //   },
      //   width: 140,
      // },
      {
        title: '备注',
        dataIndex: 'remarks',
        slotName: 'remarks',
        sortable: {
          sortDirections: ['ascend', 'descend'],
        },
        width: 180,
      },
    ],
  },
];

async function getStocktaKingWork() {
  const data = await getStocktaKingCode();
  if (data.retCode === '200') {
    workTableData.value = data.responseBody;
  } else {
    Notification.error({
      title: '盘点单号查询失败',
      content: data.message,
      closable: true,
    });
  }
}

onMounted(() => {
  getStocktaKingWork();
});

function handleClear() {
  detailTableData.value = [];
}

async function getneedCheck() {
  if (!rowClick.value) {
    Notification.error({
      title: '查询失败',
      content: '请点击盘点单号查询',
      closable: true,
    });
    return;
  }
  const data = await getMaterialsByPlan({
    stocktakingId: rowClick.value.id,
  });
  if (data.retCode === '200') {
    detailTableData.value = [];
    stocktakingId.value = rowClick.value.id;
    needCheckTableData.value = data.responseBody.detail;
    trayTableData.value = data.responseBody.workbinMaterial;
  } else {
    Notification.error({
      title: '查询失败',
      content: data.message,
      closable: true,
    });
  }
}

async function getTableData(record: any) {
  rowClick.value = record;
  if (detailTableData.value.length > 0) {
    modalVisible.value = true;
  } else {
    getneedCheck();
  }
}

const handleOk = () => {
  modalVisible.value = false;
  getneedCheck();
};
const handleCancel = () => {
  modalVisible.value = false;
};

async function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    if (needCheckTableData.value.length < 1) {
      Notification.warning({
        title: '警告',
        content: '请先点击盘点单号查询需盘物料',
        closable: true,
      });
      return;
    }
    if (materialCode.value.trim() !== '') {
      const data = await getMaterials({
        materialCode: materialCode.value,
        stocktakingId: stocktakingId.value,
      });
      if (data.retCode === '200') {
        const newMaterial = data.responseBody;
        const isDuplicate = detailTableData.value.some(
          (item) => item.materialCode === newMaterial.materialCode
        );
        if (!isDuplicate) {
          newMaterial.forEach(
            (item: { createUser: string; createTime: string }) => {
              item.createUser = getName() as string;
              // item.createTime = new Date().toLocaleString();
              detailTableData.value.push(item);
            }
          );
          materialCode.value = ''; // 清空输入框
        } else {
          Notification.warning({
            title: '警告',
            content: '该物料编码已存在',
            closable: true,
          });
          materialCode.value = ''; // 清空输入框
        }
      } else {
        Notification.error({
          title: '查询失败',
          content: data.message,
          closable: true,
        });
      }
    } else {
      Notification.warning({
        title: '警告',
        content: '请输入物料编码',
        closable: true,
      });
    }
  }
}

async function outTray() {
  const dataInfo: any[] = [];
  selectedRow.value.forEach((item_: any) => {
    if (item_.isBack !== 'N') {
      dataInfo.push({
        palletCode: item_.workbinCode || '',
        roadway: item_.rowNo || '',
        startCode: item_.shelvesCode || '',
      }); // 将匹配的项添加到数组中
    }
  });
  try {
    const data = await outBatch({ codes: dataInfo });
    if (data.retCode === '200') {
      trayTableData.value = trayTableData.value.map((item) => {
        if (
          dataInfo.some((selected) => selected.palletCode === item.workbinCode)
        ) {
          return { ...item, isBack: 'N' }; // 修改 isBack 字段
        }
        return item;
      });
      selectedKeys.value = [];
      selectedRow.value = [];
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  } catch (error) {
    Notification.error({
      title: '失败',
      content: '网络异常',
      closable: true,
    });
  }
}

async function inTray() {
  const dataInfo: any[] = [];
  selectedRow.value.forEach((item_: any) => {
    if (item_.isBack === 'N') {
      dataInfo.push({
        command: 5,
        palletCode: item_.workbinCode || '',
        // roadway: item_.rowNo || '',
        // startCode: item_.shelvesCode || '',
      }); // 将匹配的项添加到数组中
    }
  });
  const data = await inTrays({ codes: dataInfo });
  if (data.retCode === '200') {
    trayTableData.value = trayTableData.value.map((item) => {
      if (
        dataInfo.some((selected) => selected.palletCode === item.workbinCode)
      ) {
        return { ...item, isBack: 'Y' }; // 修改 isBack 字段
      }
      return item;
    });
    selectedKeys.value = [];
    selectedRow.value = [];
    Notification.success({
      title: '成功',
      content: data.message,
      closable: true,
    });
  } else {
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
  }
}

async function save() {
  // detailTableData.value.forEach((item) => {
  //   item.createTime = null;
  // });
  const data = await saveMaterials(detailTableData.value);
  if (data.retCode === '200') {
    Notification.success({
      title: '提交成功',
      content: data.message,
      closable: true,
    });
    detailTableData.value = []; // 清空输入框
    await getneedCheck();
  } else {
    Notification.error({
      title: '提交失败',
      content: data.message,
      closable: true,
    });
  }
}

watch(selectedKeys, (newKeys) => {
  if (newKeys && newKeys.length > 0) {
    selectedRow.value = trayTableData.value.filter((row) =>
      newKeys.includes(row.workbinCode)
    );
  } else selectedRow.value = [];
});
</script>

<template>
  <div class="flow-query">
    <a-card>
      <template #title>
        <div class="card-title">盘点作业</div>
      </template>
      <div class="content">
        <a-row :gutter="24">
          <a-col :span="6">
            <div class="table-container">
              <a-table
                :stripe="true"
                class="top-table"
                :pagination="false"
                :columns="workColumns"
                :data="workTableData"
                :scroll="{ y: 160 }"
                @row-click="getTableData"
              >
                <template #index="{ record }">{{
                  workTableData.indexOf(record) + 1
                }}</template>
                <template #isLarge="{ record }">{{
                  record.isLarge === 0 ? '否' : '是'
                }}</template>
              </a-table>
            </div>
          </a-col>
          <a-col :span="8">
            <div>
              <a-table
                :stripe="true"
                class="top-table"
                :pagination="false"
                :columns="needCheckColumns"
                :data="needCheckTableData"
                :scroll="{ y: 160 }"
              >
                <template #index="{ record }">{{
                  needCheckTableData.indexOf(record) + 1
                }}</template>
              </a-table>
            </div>
          </a-col>
          <a-col :span="10">
            <div class="table-container">
              <div class="button-container">
                <a-button type="primary" size="small" @click="outTray"
                  >托盘出库</a-button
                >
                <a-button type="primary" size="small" @click="inTray"
                  >托盘回库</a-button
                >
              </div>
              <a-table
                :stripe="true"
                class="top-table"
                :pagination="false"
                :columns="trayColumns"
                :data="trayTableData"
                :scroll="{ y: 160 }"
                v-model:selected-keys="selectedKeys"
                :row-selection="rowSelection"
                row-key="workbinCode"
              >
                <template #index="{ record }">{{
                  trayTableData.indexOf(record) + 1
                }}</template>
                <template #isBack="{ record }">{{
                  record.isBack === 'N' ? '出库' : '入库'
                }}</template>
              </a-table>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-top: 10px">
          <a-col :span="6">
            <a-input
              v-model="materialCode"
              allow-clear
              placeholder="请输入或扫描物料编码"
              @keydown="handleKeydown"
            ></a-input>
          </a-col>
          <a-col :span="10" style="margin-top: 5px">
            <a-link status="danger">扫码前请点击左边输入框,使其获得焦点</a-link>
          </a-col>
          <a-col :span="24">
            <div class="table-container">
              <div class="button-container2">
                <a-button
                  type="primary"
                  status="danger"
                  size="small"
                  @click="handleClear"
                  >清空</a-button
                >
                <a-button type="primary" size="small" @click="save"
                  >提交</a-button
                >
              </div>
              <a-table
                :stripe="true"
                class="top-table"
                :pagination="false"
                :columns="detailColumns"
                column-resizable
                :data="detailTableData"
                :scroll="{ y: 400 }"
                style="margin-top: 10px"
              >
                <template #index="{ record }">{{
                  detailTableData.indexOf(record) + 1
                }}</template>
                <template #qty="{ record }">
                  <a-input v-model="record.qty" />
                </template>
                <template #remarks="{ record }">
                  <a-input v-model="record.remarks" />
                </template>
              </a-table>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-card>
    <a-modal
      v-model:visible="modalVisible"
      @ok="handleOk"
      @cancel="handleCancel"
      status="warning"
    >
      <template #title> 提示 </template>
      <div>还存在未盘点物料，切换盘点单后将清空盘点明细列表，是否切换！</div>
    </a-modal>
  </div>
</template>

<style scoped>
.top-table {
  height: 100%;
}
.flow-query {
  margin: 0px;
  padding: 10px;
  height: 100%;
}
.card-title {
  font-size: 24px;
}
.content {
  display: flex;
  flex-direction: column;
}
.table-container {
  position: relative;
  overflow: hidden; /* 确保没有多余的滚动条 */
}
.button-container {
  position: absolute;
  top: 0; /* 确保按钮在表格上方 */
  right: 10px; /* 按钮在最右边 */
  z-index: 1; /* 确保按钮在表格上方 */
  margin-top: 8px; /* 向下偏移 */
  display: flex; /* 使用 flex 布局 */
  gap: 10px; /* 按钮之间的间隔 */
}
.button-container2 {
  position: absolute;
  top: 0; /* 确保按钮在表格上方 */
  right: 10px; /* 按钮在最右边 */
  z-index: 1; /* 确保按钮在表格上方 */
  margin-top: 18px; /* 向下偏移 */
  display: flex; /* 使用 flex 布局 */
  gap: 10px; /* 按钮之间的间隔 */
}
</style>
